package com.qf.service.impl;

import com.qf.pojo.User;
import com.qf.service.UserService;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/*
 *@Description:
 *@author:刘哥
 *@Date:86180 2022/9/22 16:10
 */
@Service
public class UserServiceImpl implements UserService {
    //创建 map 集合存储数据
    private final Map<Integer,User> users = new HashMap<>();
//         模拟数据库大户局
    public UserServiceImpl() {
        this.users.put(1,new User(1,"lucy","female","北京昌平","153245644"));
        this.users.put(2,new User(2,"mary","female","北京通州","165467688"));
        this.users.put(3,new User(3,"jack","male","北京西城","1324656"));
    }
    @Override
    public Mono<User> getUserById(int id) {
        return Mono.justOrEmpty(this.users.get(id));
    }

    @Override
    public Flux<User> getAllUser() {
        return Flux.fromIterable(this.users.values());
    }

    @Override
    public Mono<Void> saveUserInfo(Mono<User> user) {
        return user.doOnNext(u ->{
            int id=users.size()+1;
            users.put(id,u);
//            为空的时候 创建
        } ).thenEmpty(Mono.empty());
    }
/*
    自定义返回值类型
 */
    @Override
    public Flux<User> getUsersStream() {
//        fromIterable遍历集合创建Flux对象
//        doOnNext当订阅进入onNext状态时追加操作
        return Flux.fromIterable(this.users.values()).doOnNext(user -> {
            try {
                //模拟数据的获取需要消耗时间,一条一条的获取过来的
                Thread.sleep(3000);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

    @Override
    public User getUserById1(int id) {
        return users.get(id);
    }

    @Override
    public List<User> getAllUser1() {
        return users.values().stream().collect(Collectors.toList());
    }

    @Override
    public void saveUserInfo1(User user) {
        users.put(users.size()+1, user);
    }
}
